<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :rules="formRules"
      label-width="100px"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="规则名称" prop="ruleName">
            <el-input v-model="formData.ruleName" placeholder="请输入规则名称" />
          </el-form-item>
        </el-col>
        <el-button @click="zhinengtuijian">智能推荐</el-button>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="标签名称" prop="labelname">
            <el-input v-model="formData.labelname" :disabled="true" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="选择操作符">
            <el-tooltip
              class="box-item"
              effect="dark"
              content="或运算符：A+B 表示满足A或者B"
              placement="bottom-start"
            >
              <el-button type="primary" @click="handle('+')"> + </el-button>
            </el-tooltip>
            <el-tooltip
              class="box-item"
              effect="dark"
              content="非运算符：A-B 表示满足A且不满足B"
              placement="bottom-start"
            >
              <el-button type="primary" @click="handle('－')"> － </el-button>
            </el-tooltip>

            <el-tooltip
              class="box-item"
              effect="dark"
              content="与运算符：A*B 表示同时满足A和B"
              placement="bottom-start"
            >
              <el-button type="primary" @click="handle('*')"> * </el-button>
            </el-tooltip>

            <el-tooltip
              class="box-item"
              effect="dark"
              content="左括号：调整运算符之间的执行顺序"
              placement="bottom-start"
            >
              <el-button type="primary" @click="handle('(')"> ( </el-button>
            </el-tooltip>

            <el-tooltip
              class="box-item"
              effect="dark"
              content="右括号：调整运算符之间的执行顺序"
              placement="bottom-start"
            >
              <el-button type="primary" @click="handle(')')"> ) </el-button>
            </el-tooltip>
            <el-tooltip
              class="box-item"
              effect="dark"
              content="等号：正文=A 表示满足正文字段出现A"
              placement="bottom-start"
            >
              <el-button type="primary" @click="handle('=')"> = </el-button>
            </el-tooltip>
            <el-tooltip
              class="box-item"
              effect="dark"
              content="通配符：中？人表示两字之间可以出现一个随机字符，比如中国人"
              placement="bottom-start"
            >
              <el-button type="primary" @click="handle('?')"> ? </el-button>
            </el-tooltip>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="formData.remark" placeholder="请输入内容" type="textarea" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
  <KeyWordsTag ref="openKeywords" />
</template>
<script lang="ts" setup>
import * as BiaoqianApi from '@/api/system/biaoqian'
import KeyWordsTag from './KeyWordsTag.vue'
// import { create } from 'domain'

defineOptions({ name: 'SystemUserForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const treeData = ref([]) //树形结构展示

const formRef = ref() // 表单 Ref
/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const formData = ref({
  id: undefined,
  ruleName: '',
  labelname: '',
  remark: '',
  labelid: '' // 表单提交时对应 labelname的id(实际使用)
})
const formRules = reactive({
  type: [{ required: true, message: '请假类型不能为空', trigger: 'change' }],
  ruleName: [{ required: true, message: '规则名称不能为空', trigger: 'change' }]
})

const listBiaoqianApiParams = ref()
// const keywords = ref([]) // 关键字数组

/** 打开弹窗 ?:参数可选*/
const open = async (type: string, id?: number, data?: any) => {
  resetForm()
  // 通过传递的值给查询条件重新赋值(添加规则时 标签名称使用)
  listBiaoqianApiParams.value = { nameList: data['tamplateid'], labelname: '' }
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  if (type === 'create') {
    formData.value.labelid = String(data['id'])
    formData.value.labelname = data['name']
  }
  if (id) {
    formLoading.value = true
    try {
      formData.value = await BiaoqianApi.getRule(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  formLoading.value = true
  try {
    // 强制转换 为 RuleVO类型方便提交操作
    const data = formData.value as unknown as BiaoqianApi.RuleVO
    if (formType.value === 'create') {
      console.log(formData.value)
      await BiaoqianApi.createRule(data)
      message.success(t('common.createSuccess'))
    } else {
      await BiaoqianApi.updateRule(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    resetForm()
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    ruleName: '',
    labelname: '',
    remark: '',
    labelid: ''
  }
  formRef.value?.resetFields()
}

/** 关键字展示 */
const openKeywords = ref()

/** 选择操作符操作 + ( ) = */
const handle = (caoZuoFu: string) => {
  formData.value.ruleName = formData.value.ruleName + caoZuoFu
}
/** 智能推荐点击按钮*/
const zhinengtuijian = async () => {
  // console.log(formData.value.labelid)
  // const data = await BiaoqianApi.zhinengtuijian(formData.value.labelid)
  // keywords.value = data[0]
  // console.log(keywords.value, '--------------------------------')

  // 把规则的labelId传给KeyWordsTag.vue
  openKeywords.value.open(formData.value.labelid)
}
</script>
